<template>
  <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" style="width:80%" placeholder="1-15个字符" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" style="width:80%" placeholder="1-15个字符" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
        <el-option v-for="item in list" :key="item.id" :value="item.username" :label="item.username" />
        <!-- <el-option value="2" label="大漂亮" /> -->
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small" @click="hCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getEmployeesSimple } from '@/api/employees'
import { addDepartments, Departments, updateDepartments } from '@/api/department'
export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 手动校验
    const validCode = (rule, value, callback) => {
      // 1如果当前输入的部门存在，那么提示用户
      let exsitCodeList = this.originList.map(item => item.code)
      // 判断是否为编辑状态，如果是的，就过滤掉当前编码的状态
      if (this.isEdit) {
        exsitCodeList = this.originList.filter(item => item.id !== this.id).map(item => item.code)
        console.log(exsitCodeList, 123)
      }
      if (exsitCodeList.includes(value)) {
        // 存在的话弹出提醒
        callback(new Error(`您输入${value}的部门已经存在`))
      } else {
        // 不存在放行
        callback()
      }
    }
    // 校验部门名称在同级中是否存在（除开最上面的的添加）
    const validName = (rule, value, callback) => {
      // 1校验当前输入的部门名称存在，那么提示用户
      let exsitNameList = this.originList.filter(item => item.pid !== this.id).map(item => item.name)
      console.log(exsitNameList, 456)
      if (this.isEdit) {
        // 获取当前部门的pid
        const pid = this.originList.find(item => item.id === this.id).pid
        // 获取被占用的列表
        exsitNameList = this.originList.filter(item => item.pid === pid).filter(item => item.id !== this.id).map(item => item.name)
      }
      if (exsitNameList.includes(value)) {
        // 存在的话弹出提醒
        callback(new Error(`您输入${value}的部门已经存在`))
      } else {
        // 不存在放行
        callback()
      }
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 编码
        manager: '', // 管理者
        introduce: ''// 介绍
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 15, message: '请输入1-15个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }// 增加code的手动校验
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 1, max: 15, message: '请输入1-15个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }// 增加code的手动校验
        ],
        manager: [
          { required: true, message: '请输入部门负责人', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 300, message: '请输入1-300个字符', trigger: 'blur' }
        ]
      },
      list: []// 保存数据
    }
  },
  // 方法三 watch事件监听
  // watch: {
  //   id: function(new_value, old_value) {
  //     this.loadEmployeesSimple()
  //   }
  // },
  created() {
    this.loadEmployeesSimple()
    // 如果编辑状态  触发函数实现编辑
    if (this.isEdit) {
      this.loadDepartmentDetail()
    }
    // this.loadDepartmentDetail()
  },
  methods: {
    // 重置表单
    restForm() {
      this.$refs.deptForm.restForm()
    },
    // 获取部门详情
    async loadDepartmentDetail() {
      try {
        const res = await Departments(this.id)
        console.log(res)
        // 成功获取数据，填充到表单
        if (res.code === 10000) {
          this.form = res.data
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 加载负责人信息
    async loadEmployeesSimple() {
      try {
        const res = await getEmployeesSimple()
        console.log(res)
        this.list = res.data
      } catch (error) {
        console.log(error)
      }
    },
    // 新增子部门
    async doAdd() {
      try {
        // 合并结构要有花括号
        const res = await addDepartments({ pid: this.id, ...this.form })
        console.log(res)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.$emit('success') // 子传父
      } catch (error) {
        console.log(error)
      }
    },
    // 实现编辑部门
    async doEdit() {
      try {
        const res = await updateDepartments(this.form)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 重新渲染页面  ，，关闭弹层  前面写过，直接调用
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 确定
    hSubmit() {
      this.$refs.deptForm.validate((valid) => {
        if (!valid) return
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    // 取消
    hCancel() {
      this.$emit('close')
    }

  }
}
</script>
